<template>
    <div class="page-container">
        <div class="header">
            <h1>会员管理</h1>
            <div class="search-container">
                <input type="text" v-model="searchQuery" placeholder="搜索名称或邮箱...">
            </div>
        </div>

        <div v-if="loading" class="loading-state">正在加载会员列表...</div>
        <div v-if="error" class="error-state">{{ error }}</div>

        <div v-if="users" class="table-container">
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>用户</th>
                        <th>邮箱</th>
                        <th>手机号</th>
                        <th>会员等级</th>
                        <th>注册时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="user in filteredUsers" :key="user.userId">
                        <td>
                            <span>{{ user.userId }}</span>
                        </td>
                        <td>
                            <img :src="user.avatar || defaultAvatar" alt="User Avatar" class="user-avatar">
                            <span class="user-name">{{ user.username }}</span>
                        </td>
                        <td>{{ user.email }}</td>
                        <td>{{ user.phone || '未提供' }}</td>
                        <td>
                            <span class="level" :class="getMemberLevelClass(user.memberLevel)">
                                {{ getMemberLevelName(user.memberLevel) }}
                            </span>
                        </td>
                        <td>{{ formatDate(user.createdAt) }}</td>
                        <td>
                            <a href="#" class="action-btn" @click.prevent="viewUserDetails(user)">查看详情</a>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <!-- User Details Modal -->
        <div v-if="isModalVisible" class="modal-overlay" @click.self="closeUserDetails">
            <div class="modal-content">
                <div v-if="selectedUser" class="user-details-container">
                    <div class="modal-header">
                        <img :src="selectedUser.avatar || defaultAvatar" alt="User Avatar" class="modal-avatar">
                        <div class="modal-user-info">
                            <h2 class="modal-username">{{ selectedUser.username }}</h2>
                            <p class="modal-email">{{ selectedUser.email }}</p>
                        </div>
                        <button class="close-btn" @click="closeUserDetails">&times;</button>
                    </div>

                    <div class="modal-body">
                        <div class="details-section">
                            <h3>基本信息</h3>
                            <div class="details-grid">
                                <div class="detail-item"><strong>ID:</strong> <span>{{ selectedUser.userId }}</span></div>
                                <div class="detail-item"><strong>手机号:</strong> <span>{{ selectedUser.phone || 'N/A' }}</span></div>
                                <div class="detail-item"><strong>性别:</strong> <span>{{ selectedUser.gender || 'N/A' }}</span></div>
                                <div class="detail-item"><strong>生日:</strong> <span>{{ formatDate(selectedUser.birthday) }}</span></div>
                            </div>
                        </div>

                        <div class="details-section">
                            <h3>会员信息</h3>
                            <div class="details-grid">
                                <div class="detail-item"><strong>等级:</strong> <span>{{ getMemberLevelName(selectedUser.memberLevel) }}</span></div>
                                <div class="detail-item"><strong>积分:</strong> <span>{{ selectedUser.memberPoints || 0 }}</span></div>
                                <div class="detail-item"><strong>注册时间:</strong> <span>{{ formatDate(selectedUser.createdAt) }}</span></div>
                                <div class="detail-item"><strong>最后更新:</strong> <span>{{ formatDate(selectedUser.updatedAt) }}</span></div>
                            </div>
                        </div>

                         <div class="details-section">
                            <h3>个性签名</h3>
                            <p class="bio-text">{{ selectedUser.bio || '该用户很懒，什么都没留下。' }}</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { api } from '@/network/api';

interface User {
    userId: number;
    username: string;
    avatar: string;
    email: string;
    phone?: string;
    bio?: string;
    gender?: string;
    birthday?: string;
    memberLevel: string;
    memberPoints?: number;
    createdAt: string;
    updatedAt: string;
}

const users = ref<User[]>([]);
const loading = ref(true);
const error = ref<string | null>(null);
const defaultAvatar = '/avatar/avatar.png';
const searchQuery = ref('');

const isModalVisible = ref(false);
const selectedUser = ref<User | null>(null);

const filteredUsers = computed(() => {
    if (!searchQuery.value) {
        return users.value;
    }
    const lowerCaseQuery = searchQuery.value.toLowerCase();
    return users.value.filter(user =>
        user.username.toLowerCase().includes(lowerCaseQuery) ||
        (user.email && user.email.toLowerCase().includes(lowerCaseQuery))
    );
});

const fetchUsers = async () => {
    try {
        loading.value = true;
        const response = await api.getUsers();
        console.log("API response received:", response);
        
        const usersData = response.data?.data || response.data;
        if (Array.isArray(usersData)) {
            users.value = usersData;
        } else {
            console.error("Expected an array of users, but received:", usersData);
            users.value = [];
        }

        error.value = null;
    } catch (err) {
        console.error("获取用户列表失败:", err);
        error.value = '用户列表加载失败，请检查控制台获取详细信息。';
    } finally {
        loading.value = false;
    }
};

const getMemberLevelName = (level: string) => {
    switch (String(level)) {
        case '-2':
            return '管理员';
        case '-1':
            return '商家';
        default:
            return '顾客';
    }
};

const formatDate = (dateString?: string) => {
    if (!dateString) return 'N/A';
    const date = new Date(dateString);
    return date.toLocaleDateString();
};

const getMemberLevelClass = (level: string) => {
    switch (String(level)) {
        case '-2':
            return 'admin';
        case '-1':
            return 'merchant';
        default:
            return 'regular';
    }
};

const viewUserDetails = (user: User) => {
    selectedUser.value = user;
    isModalVisible.value = true;
};

const closeUserDetails = () => {
    isModalVisible.value = false;
    selectedUser.value = null;
};

onMounted(() => {
    fetchUsers();
});
</script>

<style scoped>
.page-container {
    padding: 30px;
}
.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}
.header h1 {
    font-size: 2em;
    font-weight: 600;
    margin: 0;
}
.search-container input {
    width: 300px;
    padding: 10px 15px;
    font-size: 1em;
    border-radius: 6px;
    border: 1px solid #ddd;
    transition: box-shadow 0.2s, border-color 0.2s;
}
.search-container input:focus {
    outline: none;
    border-color: #3498db;
    box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
}
.table-container {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
    overflow: hidden;
}
table {
    width: 100%;
    border-collapse: collapse;
}
th, td {
    padding: 15px 20px;
    text-align: left;
    border-bottom: 1px solid #f0f0f0;
    vertical-align: middle;
}
th {
    background-color: #f8f9fa;
    font-weight: 600;
    font-size: 1.2em;
    color: #555;
}
td {
    font-size: 1.2em;
}
tr:last-child td {
    border-bottom: none;
}
.user-avatar {
    width: 45px;
    height: 45px;
    object-fit: cover;
    border-radius: 50%;
    vertical-align: middle;
    margin-right: 15px;
}
.user-name {
    font-weight: 500;
}
.level {
    padding: 4px 10px;
    border-radius: 12px;
    font-size: 1.2em;
    text-transform: capitalize;
}
.level.regular {
    background-color: #eee;
    color: #555;
}
.level.gold {
    background-color: #fff0c2;
    color: #f57c00;
}
.level.platinum {
    background-color: #e0e0e0;
    color: #333;
}
.level.admin {
    background-color: #ffcdd2; /* A light red */
    color: #d32f2f;
}
.level.merchant {
    background-color: #c8e6c9; /* A light green */
    color: #388e3c;
}
.action-btn {
    color: #3498db;
    text-decoration: none;
    margin-right: 15px;
    font-size: 1.2em;
}
.action-btn:hover {
    text-decoration: underline;
}
.loading-state, .error-state {
    padding: 20px;
    text-align: center;
    font-size: 1.2em;
    color: #666;
}

/* Modal Styles */
.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
    backdrop-filter: blur(5px);
}

.modal-content {
    background: #f9f9f9;
    border-radius: 12px;
    width: 90%;
    max-width: 600px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.1);
    position: relative;
    padding: 0;
    overflow: hidden;
}

.user-details-container {
    display: flex;
    flex-direction: column;
}

.modal-header {
    background-color: white;
    padding: 20px 25px;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #eee;
    position: relative;
}

.modal-avatar {
    width: 70px;
    height: 70px;
    border-radius: 50%;
    object-fit: cover;
    margin-right: 20px;
    border: 3px solid #fff;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.modal-user-info {
    flex-grow: 1;
}

.modal-username {
    margin: 0;
    font-size: 1.8em;
    font-weight: 600;
    color: #222;
}

.modal-email {
    margin: 5px 0 0;
    color: #666;
    font-size: 1.2em;
}

.close-btn {
    position: absolute;
    top: 10px;
    right: 15px;
    background: transparent;
    border: none;
    font-size: 2.5rem;
    color: #aaa;
    cursor: pointer;
    transition: color 0.2s;
}
.close-btn:hover {
    color: #333;
}

.modal-body {
    padding: 25px;
    max-height: 60vh;
    overflow-y: auto;
}

.details-section {
    margin-bottom: 25px;
}
.details-section:last-child {
    margin-bottom: 0;
}

.details-section h3 {
    margin: 0 0 15px 0;
    font-size: 1.3em;
    font-weight: 600;
    color: #333;
    border-bottom: 1px solid #eee;
    padding-bottom: 8px;
}

.details-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 12px;
}

.detail-item {
    font-size: 1.2em;
    display: flex;
    align-items: baseline;
    line-height: 1.6;
}

.detail-item strong {
    font-weight: 600;
    color: #555;
    margin-right: 8px;
}

.detail-item span {
    color: #333;
    font-weight: 400;
}

.bio-text {
    font-size: 1.2em;
    color: #555;
    line-height: 1.6;
    margin: 0;
    white-space: pre-wrap;
    background: #fff;
    padding: 10px;
    border-radius: 6px;
    border: 1px solid #eee;
}
</style> 